package com.tarena.luban.worker.server.repository;

import com.sun.org.apache.bcel.internal.generic.RETURN;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.concurrent.TimeUnit;

public class CacheRepository<T> {
    @Autowired
    protected RedisTemplate redisTemplate;
    //单个的写
    public void set(String key, T t){
        //写到redis形成永久数据
        this.set(key,t,0l,null);
    }
    //超时写
    public void set(String key, T t, long time, TimeUnit timeUnit){
        ValueOperations opsForValue = redisTemplate.opsForValue();
        if (time==0l||timeUnit==null){
            //存储的就是永久数据
            opsForValue.set(key,t);
        }else{
            //设置超时数据
            opsForValue.set(key,t,time,timeUnit);
        }
    }
    //单个的读
    public T get(String key){
        ValueOperations opsForValue = redisTemplate.opsForValue();
        return (T) opsForValue.get(key);
    }
    //删除
    public void del(String key){
        redisTemplate.delete(key);
    }
    //抢锁
    public boolean tryLock(String lockKey){
        return redisTemplate.opsForValue().setIfAbsent(lockKey,"",10,TimeUnit.SECONDS);
    }
}
